Notice: My personal stance on AI generated artwork. Retweet and share if you agree. Let us discuss, and not immediately scream bloody murder.

Now Viewing: I made a JS script to mark favorites when searching
Keep it civil, do not flame or bait other users. If you notice anything illegal or inappropriate being discussed, contact an administrator or moderator.

karric - Group: Member - Total Posts: 1
user_avatar
I made a JS script to mark favorites when searching
Posted on: 05/05/24 02:31PM

Hi,

since it's not possible to exclude already favorited posts from search, I made a Greasemonkey userscript that adds a heart icon next to the posts that are on specific user's list of favorited posts. You need to install Greasemonkey addon (although the script doesn't use anything specific for Greasemonkey so it should work fine with other equivalents, maybe with minor changes).

On Android, Firefox Nightly app has the option of installing any addon for testing, meaning you can also run the script on an Android phone (I personally tested). I think you can also use Orbot (Tor for apps) for more privacy.

Also worth noting that I'm not a professional programmer nor English is my primary language lol

Premise of the script is actually simple: at first you NEED to change user id to the one you have (duh). It's the line with capital letters YOURIDHERE
When you visit a Gelbooru website that has any posts, it makes a couple of requests in the background to Gelbooru API, to collect IDs of specific user's favorite posts (amount of requests depends on how many favorites there are). And then attaches a heart next to the currently visible images.

It then saves data to a local session - so it stays in memory for that specific tab. I didn't want to abuse the server with constant requests, so it only checks again when you close the tab and memory gets wiped. If you add any posts to favorites, they won't show as marked until you make a new tab and start browsing there - but I think you should remember which posts you've seen already in your last session. No need to be greedy with constant checking.

To install, go to Greasemonkey extension, click New user script, paste what's below and save (click the disk icon).


// ==UserScript==
// @name GB Mark Favorites
// @version 1
// @grant none
// @include gelbooru.com/index.php?page=post*
// @require ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
// ==/UserScript==

//////////////////////////
const userid = "YOURIDHERE";
//////////////////////////

function getQueryParam(param) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(param);
}

function showHeart() {
const heartElement = document.createElement("div");
heartElement.innerHTML = "❤";
heartElement.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
font-size: 24px;
color: red;
z-index: 1000;
animation: jiggle 2.0s ease-in-out;
`;
document.body.appendChild(heartElement);

const styleSheet = document.createElement("style");
styleSheet.type = "text/css";
styleSheet.innerText = `
@keyframes jiggle {
0%, 100% { transform: rotate(0deg); }
10% { transform: rotate(10deg); }
20% { transform: rotate(-10deg); }
30% { transform: rotate(10deg); }
40% { transform: rotate(-10deg); }
50% { transform: rotate(10deg); }
60% { transform: rotate(-10deg); }
70% { transform: rotate(10deg); }
80% { transform: rotate(-10deg); }
90% { transform: rotate(10deg); }
}
`;
document.head.appendChild(styleSheet);

setTimeout(() => {
heartElement.remove();
}, 1500);
}

function setupFavlistAndMarkFavs() {
const favlist = getFavList();
if (favlist) {
markFavs(favlist);
} else {
createListFromXML().then((newFavlist) => {
sessionStorage.setItem("favlist", Array.from(newFavlist).join(","));
markFavs(newFavlist);
}).catch(error => console.error("Failed to create favlist:", error));
}
}

function getFavList() {
const tmp = sessionStorage.getItem("favlist");
if (tmp) {
return new Set(tmp.split(",").map(Number));
}
return null;
}

function markFavs(favlist) {
const viewType = getQueryParam('s');

if (viewType === 'list') {
$(".thumbnail-preview").each(function() {
const elementId = parseInt($(this).find("a").attr("id").replace('p', ''));
if (favlist.has(elementId)) {
$(this).append('<span class="favicon">❤</span>');
}
});
} else if (viewType === 'view') {
$("a[href*='index.php?page=post&s=view&id=']").each(function() {
const href = $(this).attr("href");
const idMatch = href.match(/id=(\d+)/);
if (idMatch && idMatch.length > 1) {
const linkId = parseInt(idMatch[1]);
console.log(linkId);
if (favlist.has(linkId)) {
$(this).append('<span class="favicon">❤</span>');
}
}
});
}

console.log("Marked favorites on the website");
showHeart();
}

function createListFromXML() {
return new Promise((resolve, reject) => {
const domain = "gelbooru.com/";
const limitcount = 100;
let favlist = new Set();
fetch(`${domain}index.php?page=dapi&s=post&q=index&limit=${limitcount}&json=0&pid=0&tags=fav:${userid}`)
.then(response => response.text())
.then(data => {
extractIds(data, favlist);
const totalCount = parseInt(data.match(/count="(\d+)"/)[1]);
const totalPages = Math.ceil(totalCount / limitcount);
let fetchPromises = [];
for (let i = 1; i < totalPages; i++) { fetchPromises.push(
fetch(`${domain}index.php?page=dapi&s=post&q=index&limit=${limitcount}&json=0&pid=${i}&tags=fav:${userid}`)
.then(response => response.text())
.then(pageData => extractIds(pageData, favlist))
);
}

Promise.all(fetchPromises)
.then(() => {
console.log(`Total favorite ids collected and saved to session storage: ${favlist.size}`);
resolve(favlist);
})
.catch(error => reject(error));
})
.catch(error => reject(error));
});
}


function extractIds(xmlData, favlist) {
const initialSize = favlist.size;

$(xmlData).find("id").each(function() {
favlist.add(parseInt($(this).text()));
});

const newSize = favlist.size;
}


$(document).ready(function() {
setupFavlistAndMarkFavs();
});



ThePigeon - Group: Member - Total Posts: 6847
user_avatar
Posted on: 05/05/24 02:33PM

karric said:
since it's not possible to exclude already favorited posts from search, I made a Greasemonkey userscript that adds a heart icon next to the posts that are on specific user's list of favorited posts.

Huh, neat. Good job.



add_replyAdd Reply


1